package com.amentretenimiento;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Calendar;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Competencia extends Activity implements Runnable{
	private static final int CAMERA_PIC_REQUEST = 1337; 
	private ProgressDialog pd;
	private LinearLayout ln;
	private String hora;
//	private String urlamentretenimiento="http://201.155.80.190:1863/";
	private String urlamentretenimiento=UsuariosSQLiteHelper.urlam;
//	private String urlamentretenimiento="http://201.155.80.190:8080/";
//	String urlamentretenimiento="http://www.smartthinking.com.mx:8080/";
	private String imageInSD = Environment.getExternalStorageDirectory()+"/test.jpg";
	private int numFoto=0,cancelarfoto=0;
	private SAXParserFactory spf;
	private SAXParser sp;
	private XMLReader xr ;
	private Bundle extras;
	private LoginSitesList loginsitesList = null, loginsitesList2;
	final Handler hand= new Handler();
	private int var;
	static final int DATE_DIALOG_ID = 0;
	private int mYear;
	private int mMonth;
	private int mDay;
	private EditText  precio, promocion  /*, apoyos*/;
	private String idcia, idagente, idcliente, idtipoqueja,textotitulo,textotitulocod,idprodcompet;
	private String[] arrayidCiaCompet;
	private String idformatopor,idproducto,descripcion,precios;
	private String result="";
	private String tituloEnviar,promocionesEnviar,apoyosEnviar;
	private Spinner spinner;
	private String miusuario;
	private String nombret;
	private Bitmap bm=null;
	private Dialog dialog;
	private Bitmap[] arrayFotos=null;
	private Button boton2;
	
	String nombrefoto;
	String nomtiendacod;
		
	private OrientationEventListener myOrientationEventListener;
	private int orientation = 0;
	
	
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		
		if(myOrientationEventListener!=null)
			myOrientationEventListener.disable();
		
		
    	SharedPreferences prefs =
			     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putInt("numfoto", 0);
		editor.commit();
//		Intent atras=new Intent(Competencia.this, MenuOpciones.class);
//		atras.putExtra("idagente", idagente);
//		atras.putExtra("idcliente", idcliente);
//		atras.putExtra("nombre", nombret);
//		atras.putExtra("miusuario", miusuario);
//		atras.putExtra("visitada", prefs.getInt("visitada", 0));
//
//		startActivity(atras);
	}
	

	public boolean onCreateOptionsMenu(Menu menu) {
	    super.onCreateOptionsMenu(menu);
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menucompetencia, menu);
	    return true;
	}


	public boolean onOptionsItemSelected(MenuItem item) {  
	    switch (item.getItemId()) {  
	        case R.id.menucompete:  
	        	
	          	SharedPreferences prefs =
			     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
				SharedPreferences.Editor editor = prefs.edit();
				editor.putInt("numfoto", 0);
				editor.commit();
	        	Intent intent=new Intent(Competencia.this, CompetenciasAgregadas.class);
	        	intent.putExtra("idAgente", idagente);
	        	intent.putExtra("idCia", idcia);
	        	intent.putExtra("idCliente", idcliente);
	        	intent.putExtra("nombre", nombret);
	        	intent.putExtra("miusuario", miusuario);
	        	startActivity(intent);
	        	break;
		  default:
	    }  
	    return false;  
	}


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.note_edit5);
//        Display display = getWindowManager().getDefaultDisplay(); 
//        int width = display.getWidth();  
//        int height = display.getHeight();  
//        Log.i("WIDTH", ""+width);
//        Log.i("HEIGHT", ""+height);
//        
//        if(height > 1000){
//        	 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//        }
		
		myOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL){

			@Override
			public void onOrientationChanged(int arg0) {
				Log.i("Orientation: ", ""+String.valueOf(arg0));
				orientation = arg0;
				//		     textviewOrientation.setText("Orientation: " + String.valueOf(arg0));
			}
		};


		if (myOrientationEventListener.canDetectOrientation()){
			//				Toast.makeText(this, "Can DetectOrientation", Toast.LENGTH_LONG).show();
			myOrientationEventListener.enable();
		}else{
//			Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
//			finish();
		}
		
		SharedPreferences prefs =
				getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
		nomtiendacod = remove1(prefs.getString("nombre", "nulo"));	
		Log.i("CADENACODIF", ""+nomtiendacod);
		Calendar mical=Calendar.getInstance();
		String fec=""+mical.get(Calendar.DAY_OF_MONTH)+"-"+(mical.get(Calendar.MONTH)+1)+"-"+mical.get(Calendar.YEAR);
		hora=""+mical.get(Calendar.HOUR_OF_DAY)+"-"+mical.get(Calendar.MINUTE)+"-"+mical.get(Calendar.SECOND);

		nombrefoto=nomtiendacod.toUpperCase()+fec+"_"+hora+".jpeg";
		Log.i("nombre foto", ""+nombrefoto);
		
		
		
		boolean internet = isInternetConnectionActive(Competencia.this);
		if (internet == true){
		arrayFotos=new Bitmap[2];
		Button bt=(Button) findViewById(R.id.fotos);
		bt.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			boolean internet = isInternetConnectionActive(Competencia.this);
			if (internet == true){
			Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);  
//			File file = new File(Environment.getExternalStorageDirectory(), "test.jpg");
			File file = new File(Environment.getExternalStorageDirectory()+"/AMEntretenimiento/"+nombrefoto);

			
			
			Uri outputFileUri = Uri.fromFile(file);
			cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
			Log.i("URI PHOTO", outputFileUri.toString());
			startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);  
			}else if(internet == false){
	            AlertDialog alertdialog=new AlertDialog.Builder(Competencia.this).create();
				alertdialog.setIcon(R.drawable.icon);
		    	alertdialog.setTitle("Aviso");
		    	alertdialog.setMessage("Error de conectividad");
		    	alertdialog.show();
			}
		}
	});
		
	Bundle extras = getIntent().getExtras();
	if(extras!=null){

		idproducto= extras.getString("idProducto"); 
		descripcion=extras.getString("descripcion");
		precios=extras.getString("precio");
		idcia= extras.getString("idCia"); 
		idagente= extras.getString("idAgente"); 
		idcliente= extras.getString("idCliente").trim(); 
		miusuario=extras.getString("miusuario");
		nombret=extras.getString("nombre");
		TextView nombre = (TextView) findViewById(R.id.comp);
//		SharedPreferences prefs =
//			     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
		nombre.setText(prefs.getString("nombre", "nulo"));
		precio = (EditText) findViewById(R.id.precio);
		precio.setText(""+precios);
		if(precio.getText().toString().equals("null")){
			precio.setText("");
		}
	}
	   //*********spinner de compañia con su id************//
		
	    loginsitesList=mostrarInfo();

	 	arrayidCiaCompet=new String[loginsitesList.getIdCiaCompet().size()];
	 	for(int i=0;i<arrayidCiaCompet.length;i++){
	 		arrayidCiaCompet[i]=loginsitesList.getIdCiaCompet().get(i);
	 	}
	    
	    
		String[] array;
		array=new String[loginsitesList.getnombre().size()];
		for(int i=0;i<array.length;i++){
			array[i]=loginsitesList.getnombre().get(i);
		}

			
			//*********spinner de titulo de competencias************//
			
			loginsitesList2=mostrartitulo();
			
				String[] arraytitulo;
				arraytitulo=new String[loginsitesList2.getnombre().size()];
				for(int i=0;i<arraytitulo.length;i++){
					arraytitulo[i]=loginsitesList2.getnombre().get(i);
				}
				 spinner=(Spinner) findViewById(R.id.tituloscompet);
				ArrayAdapter<String> adaptador3=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arraytitulo);
				adaptador3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				spinner.setAdapter(adaptador3);
				spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						textotitulo=	loginsitesList2.getnombre().get(arg2);	
						idprodcompet=loginsitesList2.getIdProdCompet().get(arg2);
					}
					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
					}
				});
				for(int i=0;i<arraytitulo.length;i++){
					if(arraytitulo[i].equals(descripcion)){
						spinner.setSelection(i);
					}
				}
		final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
		boton2 = (Button) findViewById(R.id.confirm);
		boton2.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				SharedPreferences prefs =
					     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
				SharedPreferences.Editor editor = prefs.edit();
				numFoto=prefs.getInt("numfoto", 0);
			
				boolean internet = isInternetConnectionActive(Competencia.this);
				if(internet==true && numFoto>0){
					precio = (EditText) findViewById(R.id.precio);
					promocion = (EditText) findViewById(R.id.promociones);
					//apoyos = (EditText) findViewById(R.id.apoyos);
					if((!precio.getText().toString().equals("")) && (!promocion.getText().toString().equals("")) /*&& (!apoyos.getText().toString().equals(""))*/)
					{

						AlertDialog.Builder builder = new AlertDialog.Builder(Competencia.this);
						builder.setMessage("�Los datos son correctos?")
						       .setCancelable(false)
						       .setPositiveButton("Si", new DialogInterface.OnClickListener() {
						           public void onClick(DialogInterface dialog, int id) {
						       		
							       		if(idproducto != null){
							       			borrarRegistro();
							    	   }
						        	   
							       		borrarRegistroInicio();
//							       		enviarInfo();
										progreso();

										}
					       })
					       .setNegativeButton("No", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					        	   dialog.cancel();
					           }
					       });
						AlertDialog alertDialog = builder.create();
						alertDialog.show();
						
					}else{
						AlertDialog.Builder builder = new AlertDialog.Builder(Competencia.this);
						builder.setMessage("Cajas de texto vacías")
						       .setCancelable(false)
						       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						           public void onClick(DialogInterface dialog, int id) {
						           }
					       });
						AlertDialog alertDialog = builder.create();
						alertDialog.show();
					}
					
				}else if(internet == false){
		            AlertDialog alertdialog=new AlertDialog.Builder(Competencia.this).create();
					alertdialog.setIcon(R.drawable.icon);
			    	alertdialog.setTitle("Aviso");
			    	alertdialog.setMessage("Error de conectividad");
			    	alertdialog.show();
				}
				else if(numFoto == 0  && cancelarfoto==0){
		            AlertDialog alertdialog=new AlertDialog.Builder(Competencia.this).create();
					alertdialog.setIcon(R.drawable.icon);
			    	alertdialog.setTitle("Aviso");
			    	alertdialog.setMessage("No se han capturado fotos");
			    	alertdialog.show();
				}				
				else if(internet==true && numFoto == 0  && cancelarfoto != 0){
					precio = (EditText) findViewById(R.id.precio);
					promocion = (EditText) findViewById(R.id.promociones);
				//	apoyos = (EditText) findViewById(R.id.apoyos);
					if((!precio.getText().toString().equals("")) && (!promocion.getText().toString().equals("")) /*&& (!apoyos.getText().toString().equals(""))*/)
					{

						AlertDialog.Builder builder = new AlertDialog.Builder(Competencia.this);
						builder.setMessage("¿Los datos son correctos?")
						       .setCancelable(false)
						       .setPositiveButton("Si", new DialogInterface.OnClickListener() {
						           public void onClick(DialogInterface dialog, int id) {
						       		
							       		if(idproducto != null){
							       			borrarRegistro();
							    	   }
						        	   
							       		borrarRegistroInicio();
										progreso();

			           
										}
					       })
					       .setNegativeButton("No", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					        	   dialog.cancel();
					           }
					       });
						AlertDialog alertDialog = builder.create();
						alertDialog.show();
						
					}else{
						AlertDialog.Builder builder = new AlertDialog.Builder(Competencia.this);
						builder.setMessage("Cajas de texto vacías")
						       .setCancelable(false)
						       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						           public void onClick(DialogInterface dialog, int id) {
						           }
					       });
						AlertDialog alertDialog = builder.create();
						alertDialog.show();
					}
					
					
				}else if(internet == false){
		            AlertDialog alertdialog=new AlertDialog.Builder(Competencia.this).create();
					alertdialog.setIcon(R.drawable.icon);
			    	alertdialog.setTitle("Aviso");
			    	alertdialog.setMessage("Error de conectividad");
			    	alertdialog.show();
				}
			}
			
		
		});
		}else if(internet == false){
            AlertDialog alertdialog=new AlertDialog.Builder(Competencia.this).create();
			alertdialog.setIcon(R.drawable.icon);
	    	alertdialog.setTitle("Aviso");
	    	alertdialog.setMessage("Error de conectividad");
	    	alertdialog.show();
		}
	
	}

            
     
	
	protected LoginSitesList mostrarInfo() {
		
		boolean internet = isInternetConnectionActive(Competencia.this);
		if (internet == true){
		LoginSitesList loginsitesList = null;

			try {
				
				/** Handling XML */
				spf = SAXParserFactory.newInstance();
				sp = spf.newSAXParser();
				xr = sp.getXMLReader();
	
				/** Send URL to parse XML Tags */
				URL sourceUrl = new URL(urlamentretenimiento+"AMEntretenimiento/DataServlet?Query=select*from+companiacompet+where+idcia="+idcia);
				
				Log.i("MII TAGG", ""+sourceUrl);
	
				/** Create handler to handle XML Tags ( extends DefaultHandler ) */
				LoginMyXMLHandler myXMLHandler = new LoginMyXMLHandler();
				xr.setContentHandler(myXMLHandler);
				xr.parse(new InputSource(sourceUrl.openStream()));
				
			} catch (Exception e) {
				System.out.println("XML Pasing Excpetion = " + e);
			}
			loginsitesList = LoginMyXMLHandler.loginsitesList;

			return loginsitesList;
		}else if(internet == false){
            AlertDialog alertdialog=new AlertDialog.Builder(Competencia.this).create();
			alertdialog.setIcon(R.drawable.icon);
	    	alertdialog.setTitle("Aviso");
	    	alertdialog.setMessage("Error de conectividad");
	    	alertdialog.show();
		}
		return loginsitesList;	
	}
	
	protected LoginSitesList mostrarformato() {
		boolean internet = isInternetConnectionActive(Competencia.this);
		if (internet == true){
		LoginSitesList loginsitesList = null;

			try {
				
				/** Handling XML */
				spf = SAXParserFactory.newInstance();
				sp = spf.newSAXParser();
				xr = sp.getXMLReader();
	
				/** Send URL to parse XML Tags */
				URL sourceUrl = new URL(urlamentretenimiento+"AMEntretenimiento/DataServlet?Query=select*from+FormatoProducto+where+idcia="+idcia);
				
				Log.i("MII TAGG", ""+sourceUrl);
	
				/** Create handler to handle XML Tags ( extends DefaultHandler ) */
				LoginMyXMLHandler myXMLHandler = new LoginMyXMLHandler();
				xr.setContentHandler(myXMLHandler);
				xr.parse(new InputSource(sourceUrl.openStream()));
				
			} catch (Exception e) {
				System.out.println("XML Pasing Excpetion = " + e);
			}
			loginsitesList = LoginMyXMLHandler.loginsitesList;
			return loginsitesList;	
			
		}else if(internet == false){
	            AlertDialog alertdialog=new AlertDialog.Builder(Competencia.this).create();
				alertdialog.setIcon(R.drawable.icon);
		    	alertdialog.setTitle("Aviso");
		    	alertdialog.setMessage("Error de conectividad");
		    	alertdialog.show();
			}
			
		return loginsitesList;			
		
		
	}
	
	protected LoginSitesList mostrartitulo() {
		boolean internet = isInternetConnectionActive(Competencia.this);
		if (internet == true){
		LoginSitesList loginsitesList = null;

			try {
				
				/** Handling XML */
				spf = SAXParserFactory.newInstance();
				sp = spf.newSAXParser();
				xr = sp.getXMLReader();
	
				/** Send URL to parse XML Tags */
				URL sourceUrl = new URL(urlamentretenimiento+"AMEntretenimiento/DataServlet?Query=select+*+from+productocompet+where+idcia="+idcia+"and+disponible=1");
				
				Log.i("MII TAGG", ""+sourceUrl);
	
				/** Create handler to handle XML Tags ( extends DefaultHandler ) */
				LoginMyXMLHandler myXMLHandler = new LoginMyXMLHandler();
				xr.setContentHandler(myXMLHandler);
				xr.parse(new InputSource(sourceUrl.openStream()));
				
			} catch (Exception e) {
				System.out.println("XML Pasing Excpetion = " + e);
			}
			loginsitesList = LoginMyXMLHandler.loginsitesList;
			return loginsitesList;			

			
		}else if(internet == false){
            AlertDialog alertdialog=new AlertDialog.Builder(Competencia.this).create();
			alertdialog.setIcon(R.drawable.icon);
	    	alertdialog.setTitle("Aviso");
	    	alertdialog.setMessage("Error de conectividad");
	    	alertdialog.show();
		}
			
		return loginsitesList;			
		
		
	}
	 
	 /*METODO PARA INSERCIÓN*/
		protected void enviarInfo() {
			boolean internet = isInternetConnectionActive(Competencia.this);
			if (internet == true){
	
			Bundle extras = getIntent().getExtras();
			if(extras!=null){
				idcia= extras.getString("idCia"); 
				idagente= extras.getString("idAgente"); 
				idcliente= extras.getString("idCliente").trim(); 
			}
			String precioom = precio.getText().toString(); 
			String promocionescom = promocion.getText().toString(); 
			 try {
				promocionesEnviar = URLEncoder.encode(promocionescom, "utf-8");
			} catch (UnsupportedEncodingException e2) {
				e2.printStackTrace();
			}
			 try {
				textotitulocod = URLEncoder.encode(textotitulo, "utf-8");
			} catch (UnsupportedEncodingException e2) {
				e2.printStackTrace();
			}

			//String apoyocom = apoyos.getText().toString(); /*OCTAVA*/
//			 try {
//				apoyosEnviar = URLEncoder.encode(apoyocom, "utf-8");
//			} catch (UnsupportedEncodingException e2) {
//				e2.printStackTrace();
//			}
			
			try {
	        InputStream is = null;
	        
	        String url =urlamentretenimiento+"AMEntretenimiento/DataServlet?" +
	        		"Command=insert+into+competenciadvdyvhs(idCliente,idCiaCompet,idFormato,Producto,Fecha,Precio,Promociones,ApoyoEspecial," +
	        		"FechaEstreno,Importante,idAgente,IdCia,Display,Cenefa,Stopper,Colgante,Standes,Poster,PapelDecorativo,Counter," +
	        		"idprodcompet)select+1,(select+idCiaCompet+from+ProductoCompet+where+idProdCompet='"+idprodcompet+"'),0,'"+textotitulocod+"',"+
	        		"getdate(),"+precioom.trim()+",'"+promocionesEnviar+"','',(select+FechaLanzamiento+from+ProductoCompet+where+idProdCompet='"+idprodcompet+"')," +
	        		"(select+importante+from+ProductoCompet+where+idProdCompet='"+idprodcompet+"'),1,3200,0,0,0,0,0,0,0,0,'"+idprodcompet+"'";
	        
	        Log.i("url mia", ""+url);
			
			URI myURI = null;
				try {
					myURI = new URI(url);
				} catch (URISyntaxException e1) {
					e1.printStackTrace();
				}
		
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet getMethod = new HttpGet(myURI);
			HttpResponse webServerResponse = null;
		
				webServerResponse = httpClient.execute(getMethod);
			HttpEntity httpEntity = webServerResponse.getEntity();

			
			if (httpEntity != null) {
				try {
					is = httpEntity.getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		            StringBuilder sb = new StringBuilder();
		            String line = null;
		            while ((line = reader.readLine()) != null) {
		                    sb.append(line + "\n");
		            }
		            is.close();
		            result=sb.toString();
					Toast.makeText(this, "Competencia agregada", Toast.LENGTH_LONG).show();
					

				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}			} catch (ClientProtocolException e) {
			} catch (IOException e) {
			}

			}else if(internet == false){
	            AlertDialog alertdialog=new AlertDialog.Builder(Competencia.this).create();
				alertdialog.setIcon(R.drawable.icon);
		    	alertdialog.setTitle("Aviso");
		    	alertdialog.setMessage("Error de conectividad");
		    	alertdialog.show();
			}
		}
		
		protected void borrarRegistroInicio() {
			boolean internet = isInternetConnectionActive(Competencia.this);
		
		Bundle extras = getIntent().getExtras();
		if(extras!=null){

			idcia= extras.getString("idCia");
			idagente= extras.getString("idAgente");
			idcliente= extras.getString("idCliente");
		}

        InputStream is = null;
        SharedPreferences prefs =
			     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);

        String url=urlamentretenimiento+"AMEntretenimiento/DataServlet?" +
        		"Command=delete+from+competenciadvdyvhs+where+IdAgente="+idagente+"+and+IdCia="+idcia+"+and+IdCliente="+prefs.getString("idcliente", "0")+"+" +
        				"and+convert(varchar,fecha,111)=convert(varchar,GETDATE(),111)and+idProdCompet="+"'"+idprodcompet+"'";
        Log.i("url mia", ""+url);
		
		URI myURI = null;
		try {
			myURI = new URI(url);
		} catch (URISyntaxException e) {
		}
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet getMethod = new HttpGet(myURI);
		HttpResponse webServerResponse = null;
		try {
			webServerResponse = httpClient.execute(getMethod);
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		}
		
		HttpEntity httpEntity = webServerResponse.getEntity();
       
		//MANEJO DE LA RESPUESTA DEL SERVIDOR
		if (httpEntity != null) {
			try {
				is = httpEntity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
	            StringBuilder sb = new StringBuilder();
	            String line = null;
	            while ((line = reader.readLine()) != null) {
	                    sb.append(line + "\n");
	            }
	            is.close();
	            result=sb.toString();

			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
		
		
			protected void borrarRegistro() {
				boolean internet = isInternetConnectionActive(Competencia.this);
				SharedPreferences prefs =
					     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
			Bundle extras = getIntent().getExtras();
			if(extras!=null){
	
				idcia= extras.getString("idCia");
				idagente= extras.getString("idAgente");
				idcliente= extras.getString("idCliente");
			}

	        InputStream is = null;
	        String url=urlamentretenimiento+"AMEntretenimiento/DataServlet?" +
	        		"Command=delete+from+competenciadvdyvhs+where+IdAgente="+idagente+"+and+IdCia="+idcia+"+and+IdCliente="+prefs.getString("idcliente", "0")+"+" +
	        				"and+convert(varchar,fecha,111)=convert(varchar,GETDATE(),111)and+idProdCompet="+idprodcompet;
	        Log.i("url mia", ""+url);
			URI myURI = null;
			try {
				myURI = new URI(url);
			} catch (URISyntaxException e) {
			}
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet getMethod = new HttpGet(myURI);
			HttpResponse webServerResponse = null;
			try {
				webServerResponse = httpClient.execute(getMethod);
			} catch (ClientProtocolException e) {
			} catch (IOException e) {
			}
			
			HttpEntity httpEntity = webServerResponse.getEntity();
	       
			//MANEJO DE LA RESPUESTA DEL SERVIDOR
			
			if (httpEntity != null) {
				try {
					is = httpEntity.getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		            StringBuilder sb = new StringBuilder();
		            String line = null;
		            while ((line = reader.readLine()) != null) {
		                    sb.append(line + "\n");
		            }
		            is.close();
		            result=sb.toString();
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
			
		}
		

		protected void onActivityResult(int requestCode, int resultCode, Intent data) {

			boolean internet = isInternetConnectionActive(Competencia.this);
			if (internet == true){
			if(resultCode==RESULT_CANCELED){
		    	Toast.makeText(getApplicationContext(), "No se ha tomado la foto", Toast.LENGTH_LONG).show();

			}
			else{
			    if (requestCode == CAMERA_PIC_REQUEST) {
			    	
			    	BitmapFactory.Options options = new BitmapFactory.Options();
			    	options.inSampleSize = 4;    
			    	
					imageInSD = Environment.getExternalStorageDirectory()+"/AMEntretenimiento/"+nombrefoto;

			    	
			    	Bitmap bmap = BitmapFactory.decodeFile(imageInSD,options);
			    	int width = bmap.getWidth();
			        int height = bmap.getHeight();
			        Log.i("Ancho de archivo", ""+width);
			        Log.i("Alto de archivo", ""+height);
			        int newWidth;
			        int newHeight;
			        if(width < height){
			        	  newWidth = 600;
					         newHeight =800 ;
			        }else{
			        	  newWidth = 800;
					         newHeight = 600;
			        }
			        float scaleWidth = ((float) newWidth) / width;
			        float scaleHeight = ((float) newHeight) / height;
			     // createa matrix for the manipulation
			        Matrix matrix = new Matrix();
			        // resize the bit map
			        matrix.postScale(scaleWidth, scaleHeight);
			        
			    	if(orientation <= 45 || (orientation> 315 && orientation<360)){
						matrix.postRotate(90);
					}else{
						matrix.postRotate(0);
					}
			    	
//			        matrix.postRotate(0);
			     // recreate the new Bitmap
			         bm = Bitmap.createBitmap(bmap, 0, 0,
			                          width, height, matrix, true);
			    	Log.i("Bitmap getWidth", ""+bm.getWidth());
			    	Log.i("Bitmap getHeight", ""+bm.getHeight());
			    	 int newWidth2,newHeight2;
				        if(bm.getWidth() < bm.getHeight()){
				        	  newWidth2 = 135;
						      newHeight2 = 181;
				        }else{
				        	  newWidth2 = 181;
						      newHeight2 = 135;

				        }
				        float scaleWidth2 = ((float) newWidth2) / width;
				        float scaleHeight2 = ((float) newHeight2) / height;
			    	 // createa matrix for the manipulation
			        Matrix matrix2 = new Matrix();
			        // resize the bit map
			        matrix2.postScale(scaleWidth2, scaleHeight2);
//			        matrix.postRotate(0);
			     // recreate the new Bitmap
			        Bitmap bmapa = Bitmap.createBitmap(bmap, 0, 0,
			                          width, height, matrix2, true);
			        dialog=new Dialog(this);
			    	dialog.setContentView(R.layout.custom_dial);
			    	dialog.setTitle("¿ Es correcta la foto ?");
			    	ImageView image = (ImageView) dialog.findViewById(R.id.imageView1);  
			    	image.setImageBitmap(bmapa); 
			    	dialog.show();
			    	
			    	Button botonina = (Button) dialog.findViewById(R.id.button1);
			    	botonina.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
								dialog.cancel();

								try {
									if(bm != null)
									{
										SharedPreferences prefs =
											     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
										SharedPreferences.Editor editor = prefs.edit();
										numFoto=prefs.getInt("numfoto", 0);
										if(numFoto>1){
											Toast.makeText(getApplicationContext(), "Número límite de fotos", Toast.LENGTH_SHORT).show();
											
										}else{
											arrayFotos[numFoto]=bm;
											for(int i=0;i<2;i++){
												Log.i("Valor arrayFotos["+i+"]", ""+arrayFotos[i]);
										
											}
											Toast.makeText(getApplicationContext(), "Foto almacenada", Toast.LENGTH_SHORT).show();
											ln = (LinearLayout) findViewById(R.id.listafotos);
											TextView txt = new TextView(getApplicationContext());
											txt.setText("foto_"+numFoto);
											txt.setTextColor(Color.BLUE);
											ln.addView(txt);
											
											
											editor.putInt("numfoto", numFoto+1);
											editor.commit();
						
											
										}

										
										
										
										
									}else{
										AlertDialog.Builder builder = new AlertDialog.Builder(Competencia.this);
										builder.setMessage("No se ha capturado la foto")
										       .setCancelable(false)
										       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
										           public void onClick(DialogInterface dialog, int id) {
										                // put your code here
										           }
										       });
										      
										AlertDialog alertDialog = builder.create();
										alertDialog.show();
										
									}
								} catch (Exception e) {
									e.printStackTrace();
								}				
							
								
							
		
						}
					});
			    	
			    	Button botootra = (Button) dialog.findViewById(R.id.button2);
			    	botootra.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
//							bm=null;
							dialog.dismiss();
							dialog.cancel();
							Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);  
//							File file = new File(Environment.getExternalStorageDirectory(), "test.jpg");
							File file = new File(Environment.getExternalStorageDirectory()+"/AMEntretenimiento/"+nombrefoto);

							Uri outputFileUri = Uri.fromFile(file);
							cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
							Log.i("URI PHOTO", outputFileUri.toString());
							startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);  
							
						}
					});
			    	
			    }
		
		    }
			}else if(internet == false){
	            AlertDialog alertdialog=new AlertDialog.Builder(Competencia.this).create();
				alertdialog.setIcon(R.drawable.icon);
		    	alertdialog.setTitle("Aviso");
		    	alertdialog.setMessage("Error de conectividad");
		    	alertdialog.show();
			}
			
			
		}
		
		protected void progreso() {
			Log.i("PROGRESO", "ENTRO");
//			pd = ProgressDialog.show(this, "Espere por favor", "Cargando..", true, false);
			pd = ProgressDialog.show(this, "Espere por favor", "Cargando..", true, true, new DialogInterface.OnCancelListener() {
				
				@Override
				public void onCancel(DialogInterface dialog) {
					onBackPressed();
				}
			});
			Thread thread = new Thread(this);
			thread.start();
		}

		@Override
		public void run() {
			try {
				Log.i("RUN", "ENTRO");

				executeMultipartPost(0);
			} catch (Exception e) {
				e.printStackTrace();
			}		
		}
		
		public void executeMultipartPost(int indice) throws Exception {

			boolean internet = isInternetConnectionActive(Competencia.this);
			try {
				refresh();
				
				Calendar mical=Calendar.getInstance();
				String fec=""+mical.get(Calendar.DAY_OF_MONTH)+"-"+(mical.get(Calendar.MONTH)+1)+"-"+mical.get(Calendar.YEAR);
				hora=""+mical.get(Calendar.HOUR_OF_DAY)+"-"+mical.get(Calendar.MINUTE)+"-"+mical.get(Calendar.SECOND);
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				arrayFotos[indice].compress(Bitmap.CompressFormat.JPEG, 50, bos);

				byte[] data = bos.toByteArray();
				HttpClient httpClient = new DefaultHttpClient();
				
				HttpPost postRequest = new HttpPost(urlamentretenimiento+"AMEntretenimiento/UploadServlet");

				MultipartEntity reqEntity = new MultipartEntity(
						HttpMultipartMode.BROWSER_COMPATIBLE);
				
				SharedPreferences prefs =
					     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
				
				String nomtiendacod = remove1(prefs.getString("nombre", "nulo"));	
				Log.i("CADENACODIF", ""+nomtiendacod);


					ByteArrayBody bab = new ByteArrayBody(data, nomtiendacod.toUpperCase()+"_"+idagente+"_"+"C"+fec+"_"+hora+".jpeg");
					Log.i("NOMBRE FOTO",nomtiendacod.toUpperCase()+"_"+idagente+"_"+"C"+fec+"_"+hora+".jpeg" );
					
					reqEntity.addPart("uploaded", bab);
					reqEntity.addPart("tipo", new StringBody("C"));
					

					
					idcia= prefs.getString("idcia", "0");
					
					Log.i("INFO", ""+idcia);
					Log.i("INFO", ""+idcliente);
					Log.i("INFO", ""+idagente);
					Log.i("INFO", ""+idprodcompet);

					
					
					reqEntity.addPart("idcia", new StringBody(idcia));
					reqEntity.addPart("idcliente", new StringBody(prefs.getString("idcliente", "0")));
					reqEntity.addPart("idagente", new StringBody(idagente));
					
					reqEntity.addPart("idproducto", new StringBody(idprodcompet));
					String precioom = precio.getText().toString(); /*SEXTA*/
					String promocionescom = promocion.getText().toString(); /*SEPTIMA*/
					//String apoyocom = apoyos.getText().toString(); /*OCTAVA*/
					reqEntity.addPart("precio", new StringBody(precioom));
					reqEntity.addPart("promociones", new StringBody(promocionescom));
					reqEntity.addPart("apoyoespecial", new StringBody(""));
					Log.i("INFO", ""+precioom);
					Log.i("INFO", ""+promocionescom);
					
					
					reqEntity.addPart("fotocompetenciacons", new StringBody(""+indice));
					postRequest.setEntity(reqEntity);
					HttpResponse response = httpClient.execute(postRequest);
					BufferedReader reader = new BufferedReader(new InputStreamReader(
							response.getEntity().getContent(), "UTF-8"));
					String sResponse;
					StringBuilder s = new StringBuilder();

					while ((sResponse = reader.readLine()) != null) {
						s = s.append(sResponse);

					}
					Log.i("Response: ", ""+s);
					if(indice<2){
						if(indice==1){
							Log.i("Indice fotos", ""+(indice+1));
						}else{
							if(arrayFotos[indice+1]!=null){
								Log.i("Indice fotos", ""+(indice+1));
								executeMultipartPost(indice+1);
							}
						}
						
					}	
					
					int signal3g=1;
				handler.sendEmptyMessage(0);


			} catch (Exception e) {
				Log.e(""+e.getClass().getName(), ""+e.getMessage());
			}

			
		}

		private Handler handler = new Handler() {
		    @Override
		    public void handleMessage(Message msg) {
				arrayFotos=new Bitmap[2];

		    	SharedPreferences prefs =
					     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
				SharedPreferences.Editor editor = prefs.edit();
				editor.putInt("numfoto", 0);
				editor.commit();
				
		            pd.dismiss();
		            Toast.makeText(getApplicationContext(), "Envío de archivo terminado", Toast.LENGTH_LONG).show();
					precio.setText("");
					promocion.setText("");
					//apoyos.setText("");
					
					ln.removeAllViews();
		            

		    }
		};
		
		
		private void refresh() {
			//delete from gps where convert(varchar,fecha,111) = convert(varchar,getdate(),111) and idAgente = 5082 and idCliente = 5988 and proceso = 'E'
			// For using Internet methods, AndroidManifest.xml must have the following permission:
			//<uses-permission android:name="android.permission.INTERNET"/>
			URI myURI = null;
			try {
				myURI = new URI(urlamentretenimiento+"AMEntretenimiento/DataServlet?Command=" +
						"delete+from+competenciadvdyvhs+where+idcliente="+idcliente+"+and+idProdCompet="+idprodcompet+"+" +
						"and+convert(varchar,Fecha,111)=convert(varchar,getdate(),111)and+idcia="+idcia+"+and+idagente="+idagente);
			} catch (URISyntaxException e) {
				// Deal with it
			}
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet getMethod = new HttpGet(myURI);
			HttpResponse webServerResponse = null;
			try {
				webServerResponse = httpClient.execute(getMethod);
				Log.i("EXECUTE GET", "URL "+urlamentretenimiento+"AMEntretenimiento/DataServlet?Command=" +
						"delete+from+competenciadvdyvhs+where+idcliente="+idcliente+"+and+idProdCompet="+idprodcompet+"+" +
						"and+convert(varchar,Fecha,111)=convert(varchar,getdate(),111)and+idcia="+idcia+"+and+idagente="+idagente);
				// Deal with it
			} catch (IOException e) {
				// Deal with it
			}
			
			HttpEntity httpEntity = webServerResponse.getEntity();
			
			if (httpEntity != null) {
				// You have your response; handle it. For instance, with an input
				// stream
				// InputStream input = entity.getContent();
			}
		
		}
		
		public static boolean isInternetConnectionActive(Context context) {
			 boolean bool = false;

			   NetworkInfo networkInfo = ((ConnectivityManager) context
	                   .getSystemService(Context.CONNECTIVITY_SERVICE))
	                   .getActiveNetworkInfo();

	                 if(networkInfo == null || !networkInfo.isConnected()) {
	                  return false;
	                 }
	                 return true;
		}
		
		public static String remove1(String input) {
            // Cadena de caracteres original a sustituir.
			String original = "áàäéèëíìïóòöúùuñÁÀÄÉÈËÍÌÏÓÒÖÚÙÜÑçÇ";		// Cadena de caracteres ASCII que reemplazar�n los originales.
			String ascii = "aaaeeeiiiooouuunAAAEEEIIIOOOUUUNcC";
            String output = input;
            for (int i=0; i<original.length(); i++) {
                // Reemplazamos los caracteres especiales.
                output = output.replace(original.charAt(i), ascii.charAt(i));
            }//for i
            return output;
        }//remove1
	
	
}
